/**
 * Created by chenzheyu on 2017/4/12.
 */
var id = window.data.id;
$(function () {


    $.ajax({
        url: ctx + '/rentvehicle/findById',
        data: {
            id: id
        },
        type: 'GET',
        success: function (data) {


            var data = data.data;
            var Datas = data;
            // console.log(data)
            var submitAjaxdata = {
                id: id,//
                name:Datas.name,//类别名称
                brandId: Datas.brandId,//品牌主键
                brandName:Datas.brandName,//品牌名称
                displacementId: Datas.displacementId,//排量id
                displacement: Datas.displacement,//排量名称
                transmissionId:Datas.transmissionId,//变速箱id
                transmission:Datas.transmission,//变速箱名称
                seat: Datas.seat,//座位数
                pregrant: '',//预授额度
                illegalDeposit: '',//违章押金
                discount:'',//折扣
                deductible: '',//不计免赔
                GPSFree: '',//GPS费用
                cap: '',//封顶
                rent: '',//租金
                typeId: Datas.typeId,//车型ID
                proportion: '',//预付现付比例
                hoildayFree: [],//节假日费用
                photos: '',//img
                refuelingFee: '',//加油费
            };
            var DefaultImage = [];
            if (data.photos !== '', data.photos) {
                DefaultImage = data.photos.split(',');
            }
            var UpLoadingoption = {
                DefaultImage: DefaultImage == '' ? [] : DefaultImage,
                UpLimit: 10,
                url: fileUploadUrl,
                onChange: function (e) {
                    submitAjaxdata.photos=e.join(",");
                }
            };
            $('.AddImgContent').UpLoading(UpLoadingoption);

            var typeId = data.typeId;
            var displacementId = data.displacementId;
            var transmissionId = data.transmissionId;
            var brandId = data.brandId;
            var holidays = data.holidays;
            $('input[name="pregrant"]').val(data.pregrant);
            $('input[name="name"]').val(data.name);
            $('input[name="illegalDeposit"]').val(data.illegalDeposit);
            $('input[name="discount"]').val(data.discount);
            $('input[name="GPSFree"]').val(data.gpsfree);
            $('input[name="advance"]').val(data.proportion);
            $('input[name="deductible"]').val(data.deductible);
            $('input[name="cap"]').val(data.cap);
            $('input[name="rent"]').val(data.rent);
            $('input[name="seat"]').val(data.seat);
            $('input[name="refuelingFee"]').val(data.refuelingFee);

            var AddCarType = $('.AddCarType');
            var NavOption = {
                data: [
                    {name: '基本信息', action: true},
                    {name: '费用设置'}
                ],
                onChange: function (data) {
                    var index = data.index;
                    var optionItem = $('.optionItem');
                    for (var i = 0; i < optionItem.length; i++) {
                        (function () {
                            var j = i;
                            optionItem.eq(j).attr('show', false);
                        })()
                    }
                    optionItem.eq(index).attr('show', true);
                    $('.Item').css('transform', 'translate(-' + (index * 50) + '%,0)')
                }
            };

            AddCarType.find('.com.ybkj.daijia.server.model.content.Content .Nav').OrderTabs(NavOption);

            $.ajax({
                url: ctx + '/rentcontent/selectAllProperty',
                data: {},
                type: 'GET',
                success: function (data) {
                    for (var i = 0; i < data.length; i++) {
                        (function () {
                            var index = i;
                            var pid = data[index].id;
                            var labels = $('<label></label>');
                            labels.append('<span class="selectName">' + data[index].propertyName + '</span><span class="pinpai text"></span>');
                            switch (data[index].seq) {
                                case 1:
                                    labels.attr('name', 'type');
                                    $.ajax({
                                        url: ctx + '/rentcontent/selectContentByPid',
                                        data: {
                                            pid: pid
                                        },
                                        type: 'GET',
                                        success: function (data) {
                                            var itemOption = {
                                                data: [],
                                                onChange: function (e) {
                                                    submitAjaxdata.type = e.text;
                                                    submitAjaxdata.typeId = e.val;
                                                }
                                            };
                                            for (var i = 0; i < data.length; i++) {
                                                (function () {
                                                    var index = i;
                                                    itemOption.data.push({
                                                        name: data[index].contentName,
                                                        Val: data[index].id
                                                    })
                                                })()
                                            }
                                            labels.find('.text').DownPullSelect(itemOption);
                                            labels.find('select').val(typeId);
                                            labels.find('select').change()
                                        }
                                    });
                                    break;
                                case 2:
                                    labels.attr('name', 'displacement');
                                    $.ajax({
                                        url: ctx + '/rentcontent/selectContentByPid',
                                        data: {
                                            pid: pid
                                        },
                                        type: 'GET',
                                        success: function (data) {
                                            var itemOption = {
                                                data: [],
                                                onChange: function (e) {
                                                    submitAjaxdata.displacement = e.text;
                                                    submitAjaxdata.displacementId = e.val;
                                                }
                                            };
                                            for (var i = 0; i < data.length; i++) {
                                                (function () {
                                                    var index = i;
                                                    itemOption.data.push({
                                                        name: data[index].contentName,
                                                        Val: data[index].id
                                                    })
                                                })()
                                            }
                                            labels.find('.text').DownPullSelect(itemOption);
                                            labels.find('select').val(displacementId);
                                            labels.find('select').change()
                                        }
                                    });
                                    break;
                                case 3:
                                    labels.attr('name', 'transmission');
                                    $.ajax({
                                        url: ctx + '/rentcontent/selectContentByPid',
                                        data: {
                                            pid: pid
                                        },
                                        type: 'GET',
                                        success: function (data) {
                                            var itemOption = {
                                                data: [],
                                                onChange: function (e) {
                                                    submitAjaxdata.transmission = e.text;
                                                    submitAjaxdata.transmissionId = e.val;
                                                }
                                            };
                                            for (var i = 0; i < data.length; i++) {
                                                (function () {
                                                    var index = i;
                                                    itemOption.data.push({
                                                        name: data[index].contentName,
                                                        Val: data[index].id
                                                    })
                                                })()
                                            }
                                            labels.find('.text').DownPullSelect(itemOption);
                                            labels.find('select').val(transmissionId);
                                            labels.find('select').change()
                                        }
                                    });
                                    break;
                                case 4:
                                    labels.attr('name', 'brandName');
                                    $.ajax({
                                        url: ctx + '/rentcontent/selectContentByPid',
                                        data: {
                                            pid: pid
                                        },
                                        type: 'GET',
                                        success: function (data) {
                                            var itemOption = {
                                                data: [],
                                                onChange: function (e) {
                                                    submitAjaxdata.brandName = e.text;
                                                    submitAjaxdata.brandId = e.val;
                                                }
                                            };
                                            for (var i = 0; i < data.length; i++) {
                                                (function () {
                                                    var index = i;
                                                    itemOption.data.push({
                                                        name: data[index].contentName,
                                                        Val: data[index].id
                                                    })
                                                })()
                                            }
                                            labels.find('.text').DownPullSelect(itemOption);
                                            labels.find('select').val(brandId);
                                            labels.find('select').change();
                                        }
                                    });
                                    break;
                            }

                            AddCarType.find('.BasicInformation').append(labels)
                        })()
                    }
                }
            });

            var holidays = data.holiday;
            $('.SetFestival .AddAction').AddCopyButton({});
            if (holidays) {
                holidays = eval('(' + holidays + ')');
                for (var i = 0; i < holidays.length; i++) {
                    (function () {
                        var index = i;
                        var holidaysTime = holidays[index];
                        label = $('<div class="label"></div>').html('' +
                            '<div class="labelContent CustomClear">' +
                            '<input class="FestivalName" type="text" name="holidaysname" placeholder="节日" value="' + holidaysTime.name + '">' +
                            '<div>：</div>' +
                            '<input class="BeginTime Time" type="text" name="beginTime" placeholder="开始时间" value="' + $().Timestamp.TimestampDate(holidaysTime.beginTime) + '">' +
                            '<div>-</div>' +
                            '<input class="EndTime Time" type="text" name="endTime" placeholder="结束时间" value="' + $().Timestamp.TimestampDate(holidaysTime.endTime) + '">' +
                            '<div>费用</div>' +
                            '<input class="Cost" type="number" name="money" placeholder="当前节日费用"  value="' + holidaysTime.money + '">' +
                            '<div>元/天</div>' +
                            '</div>' +
                            '<div class="AddAction">' +
                            '</div>');
                        label.data('id', holidays[index].id);
                        label.find('.AddAction').AddCopyButton({
                            onChange: function (e) {
                                var id = e.parent().data('id');
                                if (e.parent().data('id')) {
                                    $.ajax({
                                        url: ctx + '/rentvehicle/deleteHolidayById',
                                        data: {
                                            id: id
                                        },
                                        type: 'POST',
                                        success: function (data) {
                                            if (data.message == '删除成功') {
                                                $('body').Overlays({data: {text: '删除成功！', state: 'Ok'}})
                                            } else {
                                                $('body').Overlays({data: {text: '删除失败，请稍后重试！', state: 'No'}})
                                            }
                                        }
                                    })
                                } else {
                                    $('body').Overlays({data: {text: '删除成功！', state: 'Ok'}})
                                }

                            }
                        });
                        var beginTime = label.find('input[name="beginTime"]');
                        beginTime.datetimepicker({
                            format: "yyyy-mm-dd HH:ii",
                            language: 'zh-CN',
                            showMeridian: true,
                            autoclose: true,
                            todayBtn: true
                        });
                        beginTime.data('Time', holidaysTime.beginTime);
                        var endTime = label.find('input[name="endTime"]');
                        endTime.datetimepicker({
                            format: "yyyy-mm-dd HH:ii",
                            language: 'zh-CN',
                            showMeridian: true,
                            autoclose: true,
                            todayBtn: true
                        });
                        endTime.data('Time', holidaysTime.endTime);
                        beginTime.on('change', function (e) {
                            e.stopPropagation();
                            var Titme = beginTime.val();
                            var BreakTitme = $().Timestamp.DateTimestamp(Titme);
                            beginTime.data('Time', BreakTitme);
                        });
                        endTime.on('change', function (e) {
                            e.stopPropagation();
                            var Titme = endTime.val();
                            var BreakTitme = $().Timestamp.DateTimestamp(Titme);
                            endTime.data('Time', BreakTitme);
                        });

                        $('.SetFestivalContent').append(label);
                    })()
                }
            }


            var label = $('.SetFestivalContent').find('.label .Time');

            function AllTime() {
                label = $('.SetFestivalContent').find('.label .Time');
                if (label) {
                    for (var i = 0; i < label.length; i++) {
                        (function () {
                            var index = i;
                            label.eq(i).datetimepicker({
                                format: "yyyy-mm-dd HH:ii",
                                language: 'zh-CN',
                                showMeridian: true,
                                autoclose: true,
                                todayBtn: true
                            })
                            label.eq(i).on('change', function () {
                                var Titme = $(this).val();
                                var BreakTitme = $().Timestamp.DateTimestamp(Titme);
                                $(this).data('Time', BreakTitme)
                            });

                        })()

                    }
                }
            }

            AllTime();
            $('.ADDbutton').on('click', function () {
                label = $('<div class="label"></div>').html('' +
                    '<div class="labelContent CustomClear">' +
                    '<input class="FestivalName" type="text" name="holidaysname" placeholder="节日">' +
                    '<div>：</div>' +
                    '<input class="BeginTime Time" type="text" name="beginTime" placeholder="开始时间">' +
                    '<div>-</div>' +
                    '<input class="EndTime Time" type="text" name="endTime" placeholder="结束时间">' +
                    '<div>费用</div>' +
                    '<input class="Cost" type="number" name="money" placeholder="当前节日费用">' +
                    '<div>元/天</div>' +
                    '</div>' +
                    '<div class="AddAction">' +
                    '</div>');


                label.find('.AddAction').AddCopyButton({
                    onChange: function (e) {
                        var id = e.parent().data('id');
                        if (e.parent().data('id')) {
                            $.ajax({
                                url: ctx + '/rentvehicle/deleteHolidayById',
                                data: {
                                    id: id
                                },
                                type: 'POST',
                                success: function (data) {
                                    if (data.message == '删除成功') {
                                        $('body').Overlays({data: {text: '删除成功！', state: 'Ok'}})
                                    } else {
                                        $('body').Overlays({data: {text: '删除失败，请稍后重试！', state: 'No'}})
                                    }
                                }
                            })
                        } else {
                            $('body').Overlays({data: {text: '删除成功！', state: 'Ok'}})
                        }
                    }
                });
                var beginTime = label.find('input[name="beginTime"]');
                beginTime.datetimepicker({
                    format: "yyyy-mm-dd HH:ii",
                    language: 'zh-CN',
                    showMeridian: true,
                    autoclose: true,
                    todayBtn: true
                });
                var endTime = label.find('input[name="endTime"]');
                endTime.datetimepicker({
                    format: "yyyy-mm-dd HH:ii",
                    language: 'zh-CN',
                    showMeridian: true,
                    autoclose: true,
                    todayBtn: true
                });
                beginTime.on('change', function (e) {
                    e.stopPropagation();
                    var Titme = beginTime.val();
                    var BreakTitme = $().Timestamp.DateTimestamp(Titme);
                    beginTime.data('Time', BreakTitme);
                });
                endTime.on('change', function (e) {
                    e.stopPropagation();
                    var Titme = endTime.val();
                    var BreakTitme = $().Timestamp.DateTimestamp(Titme);
                    endTime.data('Time', BreakTitme);
                });

                $('.SetFestivalContent').append(label);
            });

            $('.CancelButton').on('click', function () {
                window.location.href = ctx + '/rentvehicle/list';
            })

            $('.OkButton').on('click', function () {

                submitAjaxdata.pregrant = $('input[name="pregrant"]').val() || null;
                submitAjaxdata.name = $('input[name="name"]').val() || null;
                submitAjaxdata.illegalDeposit = $('input[name="illegalDeposit"]').val() || null;
                submitAjaxdata.GPSFree = $('input[name="GPSFree"]').val() || null;
                submitAjaxdata.deductible = $('input[name="deductible"]').val() || null;
                submitAjaxdata.cap = $('input[name="cap"]').val() || null;
                submitAjaxdata.rent = $('input[name="rent"]').val() || null;
                submitAjaxdata.seat = $('input[name="seat"]').val() || null;
                submitAjaxdata.refuelingFee = $('input[name="refuelingFee"]').val() || null;


                var submitState = false;
                var holidaysEle = $('.SetFestivalContent .label');
                submitAjaxdata.hoildayFree = [];
                if (holidaysEle.length >= 1) {
                    for (var i = 0; i < holidaysEle.length; i++) {
                        var holidaysObj = new Object();
                        holidaysObj['money'] = holidaysEle.eq(i).find('input[name="money"]').val() || null;
                        holidaysObj['beginTime'] = holidaysEle.eq(i).find('input[name="beginTime"]').data('Time') || null;
                        holidaysObj['endTime'] = holidaysEle.eq(i).find('input[name="endTime"]').data('Time') || null;
                        holidaysObj['name'] = holidaysEle.eq(i).find('input[name="holidaysname"]').val() || null;
                        if (holidaysEle.eq(i).data('id')) {
                            holidaysObj['id'] = holidaysEle.eq(i).data('id');
                        }
                        for (key in holidaysObj) {
                            if (holidaysObj[key] == null) {
                                $('body').Overlays({data: {text: '请检查您的节假日费用信息是否填写完整！', state: 'No'}});
                                submitState = false;
                                return
                            }else if(holidaysObj.money<0){
                                $('body').Overlays({data: {text: '节假日租金不能小于0！', state: 'No'}});
                                submitState = false;
                                return
                            }
                        }
                        submitState = true;
                        submitAjaxdata.hoildayFree.push(JSON.stringify(holidaysObj));
                    }
                }

                submitAjaxdata.hoildayFree = '[' + submitAjaxdata.hoildayFree + ']';


                for (key in submitAjaxdata) {
                    if (!submitAjaxdata[key] == '' && submitAjaxdata[key]) {
                        submitState = true;
                    } else if (submitAjaxdata['hoildayFree'].length <= 0) {
                        submitState = true;
                    } else if (key == 'discount') {
                        if ($('input[name="discount"]').val()) {
                            if (parseInt($('input[name="discount"]').val()) <= 100) {
                                submitAjaxdata.discount = $('input[name="discount"]').val();
                            } else {
                                $('body').Overlays({data: {text: "请填写在线预订折扣！并且必须在100%内！", state: 'No'}});
                                return;
                            }
                        } else {
                            $('body').Overlays({data: {text: '请检查信息是否填写完整！', state: 'No'}});
                            submitAjaxdata.discount = null;
                        }
                    } else if (key == 'proportion') {
                        if ($('input[name="advance"]').val()) {
                            if (parseInt($('input[name="advance"]').val()) <= 100) {
                                submitAjaxdata.proportion = $('input[name="advance"]').val();
                            } else {
                                $('body').Overlays({data: {text: "请填写门店预付比例！并且必须在100%内！", state: 'No'}});
                                return;
                            }
                        } else {
                            $('body').Overlays({data: {text: '请检查信息是否填写完整！', state: 'No'}});
                            submitAjaxdata.proportion = null;
                        }
                    } else if (key == 'photos') {
                    } else {
                        $('body').Overlays({data: {text: '请检查信息是否填写完整！', state: 'No'}});

                        console.error(key, submitAjaxdata[key]);
                        submitState = false;
                        return;
                    }
                }



                if (submitState) {
                    $.ajax({
                        url: ctx + '/rentvehicle/updateVehicle',
                        data: submitAjaxdata,
                        type: 'POST',
                        success: function (data) {
                            if (data.message == '车系修改成功') {
                                $('body').Overlays({data: {text: '车系修改成功，即将跳转页面！', state: "Ok"}});
                                setInterval(function () {
                                    window.location.href = ctx + '/rentvehicle/list';
                                }, 2000);
                            } else {
                                $('body').Overlays({data: {text: '编辑失败，请稍后重试！', state: 'No'}})
                            }
                        }
                    })
                }

            })
        }
    });


    for(var i=0;i<$('input[type="number"]').length;i++){
        (function () {
            var index=i;
            $('input[type="number"]').eq(index).on('change',function () {
                if($(this).val()<0){
                    $(this).val(0)
                }
            })
        })()
    }
});